import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    uname: sessionStorage.getItem("uname"),
    uid: sessionStorage.getItem('uid'),
    counts: sessionStorage.getItem('counts'),

  },
  mutations: {
    setUname(state, uname) {
      state.uname = uname;
    },
    setUid(state, uid) {
      state.uid = uid;
    },
    setCounts(state, counts) {
      state.counts = counts;
    },


  },
  actions: {
    vlogin(context, user) {
      return new Promise(
        (resolve, reject) => {
          axios.post("/users/login",
            `uname=${user.uname}&upwd=${user.upwd}`
          ).then(result => {
            if (result.data.ok == 1) {
              context.commit(
                "setUid", result.data.uid
              );
              context.commit(
                "setUname", result.data.uname
              );
              resolve(result);
            } else {
              reject(result.data.msg)
            }
          })
        }
      )
    },
    vregister(context, user) {
      return new Promise(
        (resolve, reject) => {
          axios.post("/users/register",
            `uname=${user.uname}&upwd=${user.upwd}`
          ).then(result => {
            if (result.data.ok == 1) {

              resolve(result);
            } else {
              reject(result.data.msg)
            }
          })
        }
      )
    }
  },
  modules: {}
})